package com.qf.ceshi0616.category.service.impl;

import com.qf.ceshi0616.category.entity.Category;
import com.qf.ceshi0616.category.entity.CategoryVO;
import com.qf.ceshi0616.category.mapper.CategoryMapper;
import com.qf.ceshi0616.category.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author uniq7xi
 * @since 2023-06-16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryVO> getAllCategories() {
        // 查询一级分类
        List<Category> topLevelCategoryList = categoryMapper.selectCategoryByParentId(0);
        List<CategoryVO> categoryVOList = new ArrayList<>();
        // 遍历一级分类
        for (Category topLevelCategory : topLevelCategoryList) {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(topLevelCategory, categoryVO);
            // 查询二级分类
            List<Category> secondLevelCategoryList = categoryMapper.selectCategoryByParentId(topLevelCategory.getCategoryId());
            List<CategoryVO> secondLevelCategoryVOList = new ArrayList<>();
            // 遍历二级分类
            for (Category secondLevelCategory : secondLevelCategoryList) {
                CategoryVO secondLevelCategoryVO = new CategoryVO();
                BeanUtils.copyProperties(secondLevelCategory, secondLevelCategoryVO);
                // 查询三级分类
                List<Category> thirdLevelCategoryList = categoryMapper.selectCategoryByParentId(secondLevelCategory.getCategoryId());
                List<CategoryVO> thirdLevelCategoryVOList = new ArrayList<>();
                // 遍历三级分类
                for (Category thirdLevelCategory : thirdLevelCategoryList) {
                    CategoryVO thirdLevelCategoryVO = new CategoryVO();
                    BeanUtils.copyProperties(thirdLevelCategory, thirdLevelCategoryVO);
                    thirdLevelCategoryVO.setCategories(null); // 三级分类没有子分类
                    thirdLevelCategoryVOList.add(thirdLevelCategoryVO);
                }
                secondLevelCategoryVO.setCategories(thirdLevelCategoryVOList);
                secondLevelCategoryVOList.add(secondLevelCategoryVO);
            }
            categoryVO.setCategories(secondLevelCategoryVOList);
            categoryVOList.add(categoryVO);
        }
        return categoryVOList;
    }
}
